package org.ISCS.service.buildimpl;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.AuthConfig;
import com.github.dockerjava.api.model.AuthConfigurations;
import com.github.dockerjava.api.model.PushResponseItem;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.PushImageResultCallback;
import org.ISCS.entity.Dockerhub;
import org.springframework.stereotype.Service;

@Service
public class DockerHubService {
    private DockerClient dockerClient;
    private AuthConfigurations authConfigurations;

    public DockerHubService() {
        try {
            DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
                    .withDockerHost("unix:///var/run/docker.sock")
                    .withDockerTlsVerify(false)
                    .withRegistryUrl("https://registry.cn-hangzhou.aliyuncs.com/")
                    .withRegistryUsername("fremount")
                    .withRegistryPassword("Zmzzmz010627!")
                    .withRegistryEmail("3056847915@qq.com")
                    .build();
            dockerClient = DockerClientBuilder.getInstance(config).build();
        } catch (Exception e) {
            System.err.println("Error creating DockerClient: " + e.getMessage());
            e.printStackTrace();
        }

        try {
            authConfigurations = new AuthConfigurations();
            authConfigurations.addConfig(new AuthConfig().withRegistryAddress("https://registry.cn-hangzhou.aliyuncs.com/")
                    .withUsername("fremount")
                    .withPassword("Zmzzmz010627!")
                    .withEmail("3056847915@qq.com"));
        } catch (Exception e) {
            System.err.println("Error creating AuthConfigurations: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public void pushDockerImage(String imageName, Dockerhub dockerHub) {
        int result = 3;
        try {
            dockerClient.pushImageCmd(imageName)
                    .withAuthConfig(authConfigurations.getConfigs().get("https://registry.cn-hangzhou.aliyuncs.com/"))
                    .exec(new PushImageResultCallback() {
                        @Override
                        public void onNext(PushResponseItem item) {
                            super.onNext(item);
                            if (item.isErrorIndicated()) {
                                dockerHub.setDockerhubStatus(2);
                            } else {
                                dockerHub.setDockerhubStatus(1);
                            }
                        }
                    }).awaitCompletion();
        } catch (Exception e) {
            System.err.println("Error pushing Docker image: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

